import asyncio

from flask_socketio import join_room, leave_room

from rtcCVTransform.videoTans_nanodet import videoTansNanodet
from rtcCVTransform.videoTrans_Cartoon import videoTransCartoon
from rtcCVTransform.videoTrans_EdgeDetect import videoTransEdgeDetect
from rtcCVTransform.videoTrans_yolo import videoTransYolo
from serversRtc.serverRtcClient import serverRtcClient
from signaling.socketService import socketService

# key:roomId value:serverRtcClient
serverRtcCliMap = {}
MonitorRtcCliMap = {}


class serverRtcMsgWorker:

    def __init__(self):

        # self.rtcClient = serverRtcClient(videoTransYolo("/Volumes/study/objectDetection/rtcdetector/data/models/yolov5s.pt", 'cpu'))
        pass

    def enterRoom(self, userId, roomId, clientType: int = 1):
        config_path = 'nanodet/config/nanodet-m.yml'
        model_path = 'nanodet/nanodet_m.ckpt'

        # 创建serverRtcClient并放到map中
        if clientType == 1:
            rtcClient = serverRtcClient(
                roomId=roomId,
                videoTransfomer=videoTansNanodet(config_path, model_path, 'cpu'), clientType=clientType)
            serverRtcCliMap[roomId] = rtcClient
        elif clientType == 2:
            print("创建monitor rtcClient")
            rtcClient = serverRtcClient(
                roomId=roomId,
                videoTransfomer=None, clientType=clientType)
            MonitorRtcCliMap[roomId] = rtcClient
        # rtcClient = serverRtcClient(
        #         roomId=roomId,videoTransfomer=videoTransYolo("/Volumes/study/objectDetection/rtcdetector/data/models/yolov5s.pt", 'cpu'))
        # rtcClient = serverRtcClient(
        #             roomId=roomId,videoTransfomer=videoTransCartoon(),clientType=clientType)

        # 加入房间
        join_room(roomId)
        # 发送给自己joined信令
        socketService.send_to_self(socketService.SING_JOINED, userId)
        # 发送对方已经加入信令
        socketService.send_to_self(socketService.SING_OTHER_JOINED, userId)

        print("加入房间。。。")

    def leaveRoom(self, sid, roomId):
        # 离开房间
        leave_room(roomId);
        # 发给自己已离开信令
        socketService.send_to_self(socketService.SING_LEAVED, "you have leaved")
        # 发送给别人离开信令
        socketService.send_to_other(socketService.SING_OTHER_LEAVE, roomId, sid)

    def dealMessage(self, roomId, data, clientType: int = 1):

        if data['type'] == "offer":
            loop = asyncio.new_event_loop()
            if clientType == 1:
                loop.create_task(serverRtcCliMap[roomId].processOffer(roomId, data))
            elif clientType == 2:
                print("创建monitor task....")
                loop.create_task(MonitorRtcCliMap[roomId].processOffer(roomId, data))
            try:
                loop.run_forever()
            finally:
                loop.close()
